package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponse;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    MemberFeignService memberFeignService;


    @Autowired
    StringRedisTemplate redisTemplate;


    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){

        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String redisCode = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(redisCode)) {
            String l = redisCode.split("_")[1];
            long time = Long.parseLong(l);
            // 超过1分钟
            if (System.currentTimeMillis() - time <=  60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),  BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        // 验证码 再校验
        String code = UUID.randomUUID().toString().substring(0, 5);
        String value = code + "_" + System.currentTimeMillis();
        // 放入缓存 10分钟
        redisTemplate.opsForValue().set(key, value,10, TimeUnit.MINUTES);
        // 防止重复发送验证码 60s

        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }


    @GetMapping("/login.html")
    public String login(HttpSession session){
        Object loginUser = session.getAttribute(AuthServerConstant.SESSION_LOGIN_USER);
        if (loginUser == null){
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }


    @PostMapping("/register")
    public String register(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            // 转发注册页

            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 校验验证码
        String code = vo.getCode();
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone();

        String redisCode = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(redisCode)){
            if (code.equals(redisCode.split("_")[0])) {
                // 校验成功
                // 删除缓存
                redisTemplate.delete(key);
                // 调用远程服务
                R r = memberFeignService.register(vo);

                if (r.getCode() == 0) {
                    // 成功返回登录页
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", (String) r.getData(new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }
        }

        Map<String, String> errors = new HashMap<>();
        errors.put("msg","验证码错误。");
        attributes.addFlashAttribute("errors",errors);
        return "redirect:http://auth.gulimall.com/reg.html";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {

        vo.setMobile(vo.getPhone());

        // 远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0){
            MemberResponse data = (MemberResponse) login.getData("data", new TypeReference<MemberResponse>() {
            });
            session.setAttribute(AuthServerConstant.SESSION_LOGIN_USER,data);
            System.out.println("本地登录成功"+data.toString());
            return "redirect:http://gulimall.com";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", (String) login.get("msg"));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }


}
